//
//  OAuthViewController.swift
//  weibo
//
//  Created by mac on 15/12/15.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController {
    let webView = UIWebView()
    //保证安全 希望不被外界调用加private
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func defaultAccount() {
        let jsString = "document.getElementById('userId').value = '18392419910',document.getElementById('passwd').value = 'rong979963404'"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    override func loadView() {
        view = webView
        //设置代理
        webView.delegate = self
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        loadOAuthPage()
        setNavBar()
    }
    //加载授权页面
    
    private func loadOAuthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
    }
    //设置导航条
    private func setNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    }
}
//extension 使相关的代码更加模块化
extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //需要根据请求的url 去屏蔽不希望加载的界面
        guard let urlString = request.URL?.absoluteString else{
            
            return false
        }
        if urlString.hasPrefix("https://api.weibo.com/") {
            //希望加载页面
            return true
        }
        if !urlString.hasPrefix("http://www.baidu.com/") {
            //一定不是请求成功后的回调 同样也不是 我们希望加载的页面
            return false
        }
        //程序走到这里 一定是请求成功后的回调
        print(urlString)
        //解析字符串获取code码
        let query = request.URL?.query
        if let q = query {
            //字符串截取操作
            let codeStr = "code="
            let code = q.substringFromIndex(codeStr.endIndex)
            //加载用户token
            loadAccessTooken(code)
        }
        return true
    }
    //加载用户token
    private func loadAccessTooken(code: String) {
        UserAccountViewModel().loadAccessTooken(code) { (isSuccess) -> () in
            if isSuccess {
            print("登录成功")
                //动画结束的时候 发出 页面切换的通知
                //通知是同步的还是异步的
                //通知时同步的
                //这个方法是控制器dismiss掉 但是并不会立即被回收
                //model出来的也 main 注意回收 需要手动close
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    //等待被model出来的页面 彻底被回收时 再发出页面切换的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                    print("come here")
                })
                //self.close()
            }else {
            print("登录失败")
            }
        }
        
    }
}
